<?php
/**
 * 广告管理
 *
 *
 *
 *
 * @网店运维提供技术支持 授权请购买shopnc授权
 * @license    http://www.shopwwi.com
 * @link       交流群号：111731672
 */



defined('ByShopWWI') or exit('Access Invalid!');

class price_recordControl extends SystemControl{
    public function __construct(){
        parent::__construct();
        Language::read('adv');
    }

    //白银价格录入列表页 by lijianjun 2017.1.23
    public function indexOp() {
        Tpl::setDirquna('system');
        Tpl::showpage('price_record.index');
    }

    //获取列表
    public function get_price_record_xmlOp(){
        $lang = Language::getLangContent();
        $price_record  = Model('price_record');
        $condition  = array();
        if ($_POST['query'] != '' && in_array($_POST['qtype'],array('ap_name'))) {
            $condition[$_POST['qtype']] = $_POST['query'];
        }
        $sort_fields = array('ap_class','ap_display','is_use');
        if ($_POST['sortorder'] != '' && in_array($_POST['sortname'],$sort_fields)) {
            $order = $_POST['sortname'].' '.$_POST['sortorder'];
        }
        $page = new Page();
        $page->setEachNum($_REQUEST['rp']);
        $page->setStyle('admin');
        //$ap_list  = $adv->getApList($condition,$page,$order);
        //$price_record_list = $price_record->getList();
        $price_record_list = $price_record->getList($condition,$page);
        //Tpl::output('show_page',$price_record->showpage());
        //var_dump($price_record_list);exit;
        $data = array();
        $data['now_page'] = $page->get('now_page');
        $data['total_num'] = $page->get('total_num');
        foreach ((array)$price_record_list as $k => $v) {
            $list = array();
            //$operation_detail = '';
            //$list['operation'] = "<a class='btn red' onclick=\"fg_delete({$v['id']})\"><i class='fa fa-trash-o'></i>删除</a>";
            //$operation_detail = "<li><a href=\"index.php?act=adv&op=adv&ap_id={$v['id']}\"></i>管理价格</a></li>";
            $operation_detail = "<li><a href='index.php?act=price_record&op=price_record_edit&id={$v['id']}'>编辑属性</a></li>";
            //$operation_detail .= "<li><a onclick=\"copyToClipBoard('{$v['id']}');\" href=\"javascript:void(0)\">代码调用</a></li>";
            if ($operation_detail) {
                $list['operation'] = "<span class='btn'><em><i class='fa fa-cog'></i>设置 <i class='arrow'></i></em><ul>{$operation_detail}</ul>";
            }
            $list['id'] = $v['id'];
            $list['name'] = $v['name'];     //白银类型
            $list['average_price'] = $v['average_price'];     //平均价格
            $list['time'] = date('Y-m-d',$v['time']);
            //$list['ap_class'] = str_replace(array(0,1,3), array('图片','文字','Flash'),$ap_info['ap_class']);
            //$list['ap_display'] = str_replace(array(0,1,2), array($lang['ap_slide_show'],$lang['ap_mul_adv'],$lang['ap_one_adv']),$ap_info['ap_display']);
            //$list['ap_width'] = $ap_info['ap_width'];
            //$list['ap_height'] = $ap_info['ap_class'] == '1' ? '' : $ap_info['ap_height'];
            //$ap_now_count = 0;
            //$ap_count = 0;
            //$ap_now_count++;
            //$ap_count++;
            //$list['ap_count'] = $ap_count;
            //$list['ap_now_count'] = $ap_now_count;
            //$list['is_use'] = $ap_info['is_use'] ? '<span class="yes"><i class="fa fa-check-circle"></i>是</span>' : '<span class="no"><i class="fa fa-check-circle"></i>否</span>';
            $data['list'][$v['id']] = $list;
        }
        exit(Tpl::flexigridXML($data));
    }

    /**
     *
     * 新增价格
     */
    public function price_record_addOp(){
        if($_POST['form_submit'] != 'ok'){
            Tpl::setDirquna('system');
            Tpl::showpage('price_record.add');
        }else{
            $lang = Language::getLangContent();
            $price_record  = Model('price_record');
            $upload     = new UploadFile();
            $obj_validate = new Validate();
            $obj_validate->validateparam = array(
                array("input"=>$_POST["average_price"], "require"=>"true", "message"=>'请填写平均价格'),
                //array("input"=>$_POST["ap_width_media"], "require"=>"true", 'validator'=>'Number', "message"=>$lang['ap_width_must_num']),
                //array("input"=>$_POST["ap_height"], "require"=>"true", 'validator'=>'Number', "message"=>$lang['ap_height_must_num']),
                //array("input"=>$_FILES["default_pic"], "require"=>"true", "message"=>$lang['default_pic_can_not_null']),
            );
            $error = $obj_validate->validate();
            if ($error != ''){
                showMessage($error);
            }else {
                $insert_array['name']    = trim($_POST['name']);
                $insert_array['average_price']    = addslashes($_POST['average_price']);
                $insert_array['time']    = mktime(0,0,0,date("m"),date("d"),date("Y"));  //每天仅写入一次
                /*$insert_array['ap_class']   = intval($_POST['ap_class']);
                $insert_array['ap_display'] = intval($_POST['ap_display']);
                $insert_array['is_use']     = intval($_POST['is_use']);
                if($_POST['ap_width_media'] != ''){
                    $insert_array['ap_width']  = trim($_POST['ap_width_media']);
                }
                if($_POST['ap_width_word'] != ''){
                    $insert_array['ap_width']  = intval(trim($_POST['ap_width_word']));
                }
                if($_POST['default_word'] != ''){
                    $insert_array['default_content'] = trim($_POST['default_word']);
                }
                if($_FILES['default_pic']['name'] != ''){
                    $upload->set('default_dir',ATTACH_ADV);
                    $result = $upload->upfile('default_pic');
                    if (!$result){
                        showMessage($upload->error,'','','error');
                    }
                    $insert_array['default_content'] = $upload->file_name;
                }
                $insert_array['ap_height'] = trim($_POST['ap_height']);*/
                //查询时间是否存在 时间唯一
                $count = Model()->table('price_record')->where(array('time'=>addslashes($insert_array['time']),'name'=>addslashes($insert_array['name'])))->count();
                //如果已经写入，则跳回
                if($count>=1){
                    showMessage('一天只可以写入一条记录','index.php?act=price_record&op=index','html','succ',1,4000);
                }else{
                    $result  = $price_record->price_record_add($insert_array);
                    if ($result){
                        $this->log('['.$_POST["name"].']'.' 价格写入成功',null);
                        showMessage('白银价格写入成功','index.php?act=price_record&op=index','html','succ',1,4000);
                    }else {
                        showMessage('白银价格写入失败');
                    }
                }
            }
        }
    }

    /**
     *
     * 修改价格
     */
    public function price_record_editOp(){
        if (empty($_GET['id'])) {
            showMessage('参数错误');
        }
        if($_POST['form_submit'] != 'ok'){
            $price_record  = Model('price_record');
            $id = intval($_GET['id']);
            //$condition['id']=$id;
            //$adv_list = $adv->getList($condition);
            $price_record_info  = $price_record->getOneById($id);
            //$price_record_info  = $price_record->getList($condition);
            //var_dump($price_record_info);exit;
            Tpl::output('ref_url',getReferer());
            //Tpl::output('adv_list',$adv_list);
            Tpl::output('price_record_info',$price_record_info);
            Tpl::setDirquna('system');
            Tpl::showpage('price_record.edit');
        }else{
            $lang = Language::getLangContent();
            $price_record  = Model('price_record');
            $upload     = new UploadFile();
            /**
             * 验证
             */
            $obj_validate = new Validate();
            $obj_validate->validateparam = array(
                array("input"=>$_POST["average_price"], "require"=>"true", "message"=>'请填写价格'),
                //array("input"=>$_POST["adv_start_date"], "require"=>"true","message"=>$lang['must_select_start_time']),
                //array("input"=>$_POST["adv_end_date"], "require"=>"true", "message"=>$lang['must_select_end_time'])
            );
            $error = $obj_validate->validate();
            if ($error != ''){
                showMessage($error);
            }else {
                $param['id']         = intval($_GET['id']);
                $param['name']      = trim($_POST['name']);
                $param['average_price']      = addslashes($_POST['average_price']);
                $result = $price_record->updates($param);

                if ($result){
                    $url = array(
                        array(
                            'url'=>trim($_POST['ref_url']),
                            'msg'=>'回到列表',
                        )
                    );
                    $this->log('['.$_POST["name"].']'.'修改成功',null);
                    showMessage('修改成功',$url);
                }else {
                    showMessage('修改失败',trim($_POST['ref_url']));
                }
            }
        }
    }

    /**
     * js代码调用
     */
    public function ap_copyOp(){
		Tpl::setDirquna('system');
        Tpl::showpage('ap_copy', 'null_layout');
    }

    public function deleteOp() {
         if (preg_match('/^[\d,]+$/', $_GET['del_id'])) {
            $adv = Model('adv');
            $where  = "where adv_id in (".$_GET['del_id'].")";
            Model('adv')-> ap_del("adv",$where);
            foreach (explode(',',$_GET['del_id']) as $v) {
                if (!empty($v)) {
                    $result  = $adv->ap_del(intval($v));
                }
            }
            $this->log('删除广告位成功'.'[ID:'.$_GET['del_id'].']',null);
            exit(json_encode(array('state'=>true,'msg'=>'删除成功')));
        } else {
            exit(json_encode(array('state'=>false,'msg'=>'删除失败')));
        }
    }

    public function adv_deleteOp() {
        if (preg_match('/^[\d,]+$/', $_GET['del_id'])) {
            $adv = Model('adv');
            $where  = "where adv_id in (".$_GET['del_id'].")";
            Model('adv')-> adv_del("adv",$where);
			
            foreach (explode(',',$_GET['del_id']) as $v) {
                if (!empty($v)) {
                    $result  = $adv->adv_del(intval($v));
                }
            }
            $this->log('删除广告成功'.'[ID:'.$_GET['del_id'].']',null);
            exit(json_encode(array('state'=>true,'msg'=>'删除成功')));
        } else {
            exit(json_encode(array('state'=>false,'msg'=>'删除失败')));
        }
    }

    /**
     *
     * 广告管理
     */
    public function advOp(){
        Tpl::output('ap_name',Model()->table('adv_position')->getfby_ap_id(intval($_GET['ap_id']),'ap_name'));
		Tpl::setDirquna('system');
        Tpl::showpage('adv.index');
    }

    public function get_adv_xmlOp(){
        $lang = Language::getLangContent();
        $adv  = Model('adv');
        $condition  = array();
        $condition['ap_id'] = intval($_GET['ap_id']);
        if ($_POST['query'] != '' && in_array($_POST['qtype'],array('adv_title'))) {
            $condition[$_POST['qtype']] = $_POST['query'];
        }
        $sort_fields = array('ap_id','adv_start_date','adv_end_date');
        if ($_POST['sortorder'] != '' && in_array($_POST['sortname'],$sort_fields)) {
            $order = $_POST['sortname'].' '.$_POST['sortorder'];
        }
        $condition['is_allow'] = '1';
        $page = new Page();
        $page->setEachNum($_POST['rp']);
        $page->setStyle('admin');
        $adv_list  = $adv->getList($condition,$page,'',$order);
        $ap_list = $adv->getApList();
        $data = array();
        $data['now_page'] = $page->get('now_page');
        $data['total_num'] = $page->get('total_num');
        foreach ((array)$adv_list as $k => $adv_info) {
            $list = array();$operation_detail = '';
            $list['operation'] = "<a class='btn red' onclick=\"fg_delete({$adv_info['adv_id']})\"><i class='fa fa-trash-o'></i>删除</a><a class='btn blue' href='index.php?act=adv&op=adv_edit&adv_id={$adv_info['adv_id']}'><i class='fa fa-pencil-square-o'></i>编辑</a>";
            $list['adv_title'] = $adv_info['adv_title'];
            $list['ap_id'] = $list['ap_class'];
            $list['ap_class'] = '';
            foreach ($ap_list as $ap_k => $ap_v){
                if($adv_info['ap_id'] == $ap_v['ap_id']){
                    $list['ap_id'] = $ap_v['ap_name'];
                    $list['ap_class'] = str_replace(array(0,1,3), array('图片','文字','Flash'),$ap_v['ap_class']);
                    break;
                }
            }
            $list['adv_start_date'] = date('Y-m-d',$adv_info['adv_start_date']);
            $list['adv_end_date'] = date('Y-m-d',$adv_info['adv_end_date']);
            $data['list'][$adv_info['adv_id']] = $list;
        }
        exit(Tpl::flexigridXML($data));
    }



    /**
     *
     * 获取UNIX时间戳
     */
    public function getunixtime($time){
        $array     = explode("-", $time);
        $unix_time = mktime(0,0,0,$array[1],$array[2],$array[0]);
        return $unix_time;
    }

    /**
     *
     * ajaxOp
     */
    public function ajaxOp(){
        switch ($_GET['branch']){
            case 'is_use':
            $adv=Model('adv');
            $param[trim($_GET['column'])]=intval($_GET['value']);
            $param['ap_id']=intval($_GET['id']);
            $adv->ap_update($param);

            echo 'true';exit;
            break;
        }
    }
}
